<template>
	<div class="layout-padding">
		<splitpanes>
			<pane>
				<div class="layout-padding-auto layout-padding-view">
					<!-- 头部数据展示 -->
					<div class="user-top flex mb-5 gap-5 justify-between">
						<div class="topName flex items-center" v-for="item in toplist" :key="item.name">
							<img class="ml-7 mr-6 w-12 h-14" :src="`/src/assets/user/${item.name}.png`" alt="" />
							<span>{{ item.name }}</span>
							<span class="top-num">{{ item.num }}</span>
						</div>
					</div>

					<div class="p-5 pt-0 flex flex-col h-full" style="background: #ffffff">
						<!-- 列表导航 -->
						<div class="flex h-16 items-center">
							<el-row class="mr-16">
								<div
									class="w-36 h-10 cursor-pointer flex justify-center items-center gap-2"
									style="background: #5a78b7; color: #fff; border-radius: 4px"
									@click="userDialogRef.openDialog()"
								>
									<img src="/src/assets/user/创建用户.png" class="custom-icon" alt="add" />
									<span>创建用户</span>
								</div>
							</el-row>
							<el-row v-show="showSearch" class="gap-7">
								<el-form-item :label="$t('sysuser.username')" prop="username">
									<el-input v-model="state.queryForm.username" />
								</el-form-item>
								<el-form-item :label="$t('sysuser.phone')" prop="phone">
									<el-input v-model="state.queryForm.phone" />
								</el-form-item>
								<el-form-item label="用户角色" prop="js">
									<el-input v-model="state.queryForm.phone" />
								</el-form-item>
								<el-form-item label="用户状态" prop="lockFlag">
									<el-select v-model="state.queryForm.lockFlag" clearable placeholder="请选择用户状态">
										<el-option label="正常" value="0"></el-option>
										<el-option label="锁定" value="9"></el-option>
										<el-option label="冻结" value="10"></el-option>
									</el-select>
								</el-form-item>
							</el-row>

							<div class="absolute right-5">
								<el-button class="btnReset" @click="resetQuery">{{ $t('common.resetBtn') }}</el-button>
								<el-button class="btnSearch" @click="getDataList">{{ $t('common.queryBtn') }}</el-button>
							</div>
						</div>

						<el-table
							v-loading="state.loading"
							:data="state.dataList"
							@selection-change="handleSelectionChange"
							:cell-style="tableStyle.cellStyle"
							stripe
							:header-cell-style="tableStyle.headerCellStyle"
						>
							<el-table-column :label="$t('sysuser.username')" prop="username" fixed="left" show-overflow-tooltip></el-table-column>
							<el-table-column label="用户ID" prop="userId" show-overflow-tooltip></el-table-column>
							<el-table-column label="用户角色" show-overflow-tooltip width="200">
								<template #default="scope">
									<div class="relative w-full min-h-4">
										<!-- 显示前4个标签 -->
										<template v-for="(item, index) in scope.row.roleList" :key="index">
											<el-tag v-if="index == 0" class="mr-2">{{ item.roleName }}</el-tag>
										</template>
										<!-- 超出4个标签时显示省略号 -->
										<el-popover placement="top" :width="200" trigger="hover" v-if="scope.row.roleList && scope.row.roleList.length > 1">
											<template #reference>
												<el-tag>...</el-tag>
											</template>
											<div class="flex gap-2 flex-wrap">
												<el-tag v-for="(item, index) in scope.row.roleList.slice(1)" :key="index">
													{{ item.roleName }}
												</el-tag>
											</div>
										</el-popover>

										<el-icon
											size="14"
											color="#3156A5"
											style="position: absolute; top: 50%; transform: translate(-50%, -50%)"
											class="ml-4 cursor-pointer right-0"
											@click="userDialogRef.editDialog(scope.row)"
										>
											<EditPen />
										</el-icon>
									</div>
								</template>
							</el-table-column>
							<el-table-column label="注册手机号" prop="phone" show-overflow-tooltip></el-table-column>
							<el-table-column label="填写职业" prop="occupation" show-overflow-tooltip></el-table-column>
							<el-table-column label="注册日期" prop="createTime" show-overflow-tooltip></el-table-column>
							<el-table-column label="最后活跃时间" prop="lastLoginTime" show-overflow-tooltip></el-table-column>
							<el-table-column label="空间使用情况" prop="usedSpaceSizeFormat" width="250">
								<template #default="scope">
									<div class="space-progress-container">
										<el-progress :percentage="calculatePercentage(scope.row.usedSpaceSizeFormat, scope.row.spaceSize)" :stroke-width="10" />
									</div>
								</template>
							</el-table-column>
							<el-table-column label="用户状态" prop="lockFlag">
								<template #default="scope">
									<div class="flex justify-center">
										<div class="lockName" :class="scope.row.lockFlag == 0 ? 'normal' : 'locked'">
											{{ scope.row.lockFlag == 0 ? '正常' : scope.row.lockFlag == 9 ? '锁定' : '冻结' }}
										</div>
									</div>
								</template>
							</el-table-column>
							<el-table-column label="管理">
								<template #default="scope">
									<div class="flex justify-center w-full">
										<span
											class="recoverName cursor-pointer"
											v-if="scope.row.lockFlag == 9 || scope.row.lockFlag == 10"
											@click="handleRecover(scope.row)"
											>恢复</span
										>
										<span class="logoutName cursor-pointer" v-if="scope.row.lockFlag == 0" @click="handleRecover(scope.row)">冻结</span>
									</div>
								</template>
							</el-table-column>
						</el-table>
						<pagination class="relative" v-bind="state.pagination" @current-change="currentChangeHandle" @size-change="sizeChangeHandle">
						</pagination>
					</div>
				</div>
			</pane>
		</splitpanes>

		<user-form ref="userDialogRef" @refresh="getDataList(false)" />
		<!-- 冻结用户 -->
		<el-dialog :close-on-click-modal="false" width="347px" v-model="visible" :title="editForm.lockFlag == 0 ? '冻结用户' : '恢复用户'">
			<div class="flex justify-center mb-8" style="font-weight: 500; font-size: 14px; color: #474c65">
				<el-icon size="21" class="mr-4"><WarningFilled /></el-icon>
				<p>确认{{ editForm.lockFlag == 0 ? '冻结用户' : '恢复用户' }}"{{ editForm.username }}"?</p>
			</div>
			<div class="flex justify-center">
				<el-button class="btnClose" @click="visible = false">{{ $t('common.cancelButtonText') }}</el-button>
				<el-button class="btnSave" @click="handleEdit(editForm.lockFlag)">{{ $t('common.confirmButtonText') }}</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script lang="ts" name="systemUser" setup>
import { delObj, pageList, putObj, getStatis, getRoleList } from '/@/api/admin/user';
import { deptTree } from '/@/api/admin/dept';
import { BasicTableProps, useTable } from '/@/hooks/table';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { useI18n } from 'vue-i18n';

// 动态引入组件
const UserForm = defineAsyncComponent(() => import('./form.vue'));
const QueryTree = defineAsyncComponent(() => import('/@/components/QueryTree/index.vue'));

const { t } = useI18n();
const editForm = ref({});
// 定义变量内容
const userDialogRef = ref();
const excelUploadRef = ref();
const queryRef = ref();
const visible = ref(false);
const showSearch = ref(true);
const toplist = ref([
	{
		name: '已注册用户',
		img: '',
		num: 160,
	},
	{
		name: '普通用户',
		img: '',
		num: 160,
	},
	{
		name: '订阅用户',
		img: '',
		num: 160,
	},
	{
		name: '近7天活跃用户',
		img: '',
		num: 160,
	},
]);
// 多选rows
const selectObjs = ref([]) as any;
// 是否可以多选
const multiple = ref(true);

// 定义表格查询、后台调用的API
const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {
		deptId: '',
		username: '',
		phone: '',
	},
	pageList: pageList,
});
const { getDataList, currentChangeHandle, sizeChangeHandle, downBlobFile, tableStyle } = useTable(state);

// 部门树使用的数据
const deptData = reactive({
	queryList: (name: String) => {
		return deptTree({
			deptName: name,
		});
	},
});
//获取用户统计数据
const userData = async () => {
	const { data } = await getStatis({});
	toplist.value[0].num = data.total;
	toplist.value[2].num = data.vipCount;
	toplist.value[1].num = data.generalCount;
	toplist.value[3].num = data.pastSevenDayActivityCount;
};
const calculatePercentage = (usedSpace: string, totalSpace: string) => {
	if (!totalSpace || totalSpace === '0') return 0;
	const used = parseFloat(usedSpace) || 0;
	const total = parseFloat(totalSpace) || 1;
	return Math.min(100, Math.round((used / total) * 100));
};

const formatSpaceSize = (size: string) => {
	if (!size) return '0M';
	const sizeNum = parseInt(size);
	if (sizeNum >= 1024 * 1024 * 1024) {
		return `${(sizeNum / (1024 * 1024 * 1024)).toFixed(2)}G`;
	} else if (sizeNum >= 1024 * 1024) {
		return `${(sizeNum / (1024 * 1024)).toFixed(2)}M`;
	} else if (sizeNum >= 1024) {
		return `${(sizeNum / 1024).toFixed(2)}K`;
	} else {
		return `${sizeNum}B`;
	}
};
const handleRecover = (row) => {
	editForm.value = row;
	visible.value = true;
};
// 清空搜索条件
const resetQuery = () => {
	state.queryForm = {};
	getDataList();
};
const handleEdit = (flag) => {
	const { userId } = editForm.value;
	putObj({ userId, lockFlag: flag == 0 ? '10' : '0' });
	useMessage().success('修改成功');
	visible.value = false;
	getDataList();
};
// 点击树
const handleNodeClick = (e: any) => {
	state.queryForm.deptId = e.id;
	getDataList();
};
//修改角色
const handleRole = (row) => {};
// 导出excel
const exportExcel = () => {
	downBlobFile('/admin/user/export', state.queryForm, 'users.xlsx');
};

// 是否可以多选
const handleSelectable = (row: any) => {
	return row.username !== 'admin';
};

// 多选事件
const handleSelectionChange = (objs: { userId: string }[]) => {
	selectObjs.value = objs.map(({ userId }) => userId);
	multiple.value = !objs.length;
};

// 删除操作
const handleDelete = async (ids: string[]) => {
	try {
		await useMessageBox().confirm(t('common.delConfirmText'));
	} catch {
		return;
	}

	try {
		await delObj(ids);
		getDataList();
		useMessage().success(t('common.delSuccessText'));
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};

//表格内开关 (用户状态)
const changeSwitch = async (row: object) => {
	await putObj(row);
	useMessage().success(t('common.optSuccessText'));
	getDataList();
};
userData();
</script>

<style lang="scss" scoped>
.topName {
	width: 24%;
	height: 80px;
	background: #ffffff;
	border-radius: 8px 8px 8px 8px;
	font-weight: bold;
	font-size: 18px;
	color: #474c65;
	position: relative;
	.top-num {
		font-weight: 800;
		font-size: 28px;
		color: #4267b7;
		position: absolute;
		right: 64px;
	}
}
:deep(.el-form-item--default) {
	margin-bottom: 0px;
}
:deep(.el-table) {
	height: 82%;
}
.recoverName {
	font-weight: 500;
	font-size: 14px;
	color: #1f86ff;
	text-decoration-line: underline;
}
.logoutName {
	font-weight: 500;
	font-size: 14px;
	color: #ff5b5b;
	text-decoration-line: underline;
}
.tagName {
	height: 24px;
	padding: 2px 8px;
	text-align: center;
	font-weight: 500;
	font-size: 14px;
	color: #1f86ff;
	background: rgba(192, 223, 255, 0.8);
	border-radius: 4px 4px 4px 4px;
}
.lockName {
	width: 60px;
	height: 24px;
	line-height: 24px;
	text-align: center;
	border-radius: 20px 20px 20px 20px;
}
.normal {
	background: rgba(181, 240, 185, 0.8);
	color: #29b220;
}
.locked {
	background: rgba(255, 226, 210, 0.8);
	color: #e86a23;
}
:deep(.el-pagination__total) {
	position: absolute;
	left: 0px;
}
:deep(.el-progress-bar) {
	.el-progress-bar__outer {
		border-radius: 4px;
	}

	.el-progress-bar__inner {
		border-radius: 4px;
	}
}
.space-progress-container {
	padding: 0 10px;

	.space-text {
		display: flex;
		justify-content: space-between;
		margin-top: 4px;
		font-size: 12px;
		color: #606266;
	}

	.space-usage {
		text-align: center;
		font-size: 12px;
		color: #606266;
		margin-top: 2px;
	}
}
</style>
